package top.lcm889.juc.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableDemo {
    public static void main(String[] args) {
        // 创建Callable对象
        CallableThread ct1 = new CallableThread();
        // 使用FutureTask来包装Callable对象
        FutureTask<Integer> task = new FutureTask<Integer>(ct1);
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + "循环变量的值： " + i);
            if (i == 20) {
                // 实质还是Callable对象来创建、并启动线程
                new Thread(task, "有返回值的线程： ").start();
            }
        }
        try {
            // 获取callable线程的返回值
            System.out.println("子线程的返回值：" + task.get());
        }catch (Exception E) {
            E.printStackTrace();
        }

    }
}

class CallableThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 100; i++) {
            System.out.println(Thread.currentThread().getName() + " 循环变量的值: " + i);
        }
        // call方法可以有返回值
        return  i;
    }
}
